<script setup>
import {
  // getSubCategoryAPI,
  queryProductsByCategoryAndBrand,
  queryBrandsByCategory,
  queryCategoriesByBrand
} from '@/apis/category'
import { ref, onMounted } from 'vue'
// import { useRoute } from 'vue-router'

// 获取分类面包屑导航数据
// const subCategoryList = ref({})
// const route = useRoute()
// const getSubCategory = async () => {
//   const res = await getSubCategoryAPI(route.params.id)
//   subCategoryList.value = res.result
// }
// getSubCategory()

// 查询条件
const categories = ref([])
const brands = ref([])
const goodList = ref([])

// 分页参数
const pageSize = ref(10) // 每页显示数量
const currentPage = ref(1) // 当前页码
const total = ref(0) // 总商品数

// 表单数据
const queryForm = ref({
  categoryId: '',
  brandId: ''
})

// 获取品牌列表
const fetchBrands = async () => {
  if (!queryForm.value.categoryId) {
    brands.value = [] // 清空品牌列表
    return
  }
  try {
    const res = await queryBrandsByCategory(queryForm.value.categoryId)
    brands.value = res.data || []
  } catch (error) {
    console.error('fetchBrands Error:', error) // 打印错误信息
  }
}

// 获取分类列表
const fetchCategories = async () => {
  if (!queryForm.value.brandId) {
    categories.value = [] // 清空分类列表
    return
  }
  try {
    const res = await queryCategoriesByBrand(queryForm.value.brandId)
    categories.value = res.data || []
  } catch (error) {
    console.error('fetchCategories Error:', error) // 打印错误信息
  }
}

// 查询商品方法
const queryProducts = async () => {
  try {
    const res = await queryProductsByCategoryAndBrand(
      queryForm.value.categoryId,
      queryForm.value.brandId,
      currentPage.value, // 当前页码
      pageSize.value // 每页大小
    )
    goodList.value = res.data.list // 商品数据
    total.value = res.data.total // 总数据量
  } catch (error) {
    console.error('查询失败', error) // 错误处理
  }
}

// 页面加载时调用查询功能
onMounted(async () => {
  // 默认加载所有分类和品牌
  await fetchDefaultCategories()
  await fetchDefaultBrands()
  queryProducts()
})

const fetchDefaultCategories = async () => {
  try {
    const res = await queryCategoriesByBrand('') // 获取所有分类
    categories.value = res.data || []
  } catch (error) {
    console.error('Failed to fetch default categories:', error)
    categories.value = []
  }
}

const fetchDefaultBrands = async () => {
  try {
    const res = await queryBrandsByCategory('') // 获取所有品牌
    brands.value = res.data || []
  } catch (error) {
    console.error('Failed to fetch default brands:', error)
    brands.value = []
  }
}

const resetForm = async () => {
  // 清空表单字段
  queryForm.value.categoryId = ''
  queryForm.value.brandId = ''

  // 清空表单关联数据
  goodList.value = []

  // 重新加载默认分类和品牌
  await fetchDefaultCategories()
  await fetchDefaultBrands()

  // 重置分页
  currentPage.value = 1

  // 再次调用查询，刷新商品列表
  queryProducts()
}

// 页码改变时触发的事件
const handlePageChange = (page) => {
  currentPage.value = page
  queryProducts()
}
// 每页显示数量改变时触发的事件
const handlePageSizeChange = (size) => {
  pageSize.value = size
  queryProducts()
}
</script>

<template>
  <div class="container">
    <!-- 查询表单 -->
    <div class="filter-container">
      <el-form :model="queryForm" inline>
        <!-- 分类选择 -->
        <el-form-item label="分类">
          <el-select
            v-model="queryForm.categoryId"
            placeholder="选择分类"
            @change="fetchBrands"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <!-- 品牌选择 -->
        <el-form-item label="品牌">
          <el-select
            v-model="queryForm.brandId"
            placeholder="选择品牌"
            @change="fetchCategories"
          >
            <el-option
              v-for="brand in brands"
              :key="brand.id"
              :label="brand.name"
              :value="brand.id"
            />
          </el-select>
        </el-form-item>
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="queryProducts">查询</el-button>
          <el-button @click="resetForm">清空</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品列表 -->
    <div class="sub-container">
      <div class="body">
        <goods-item
          v-for="good in goodList"
          :key="good.id"
          :good="good"
        ></goods-item>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-if="goodList.length > 0"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange"
        @size-change="handlePageSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.bread-container {
  padding: 25px 0;
  color: #666;
}

.sub-container {
  padding: 20px 10px;
  background-color: #fff;

  .body {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10px;
  }

  .goods-item {
    display: block;
    width: 220px;
    margin-right: 20px;
    padding: 20px 30px;
    text-align: center;

    img {
      width: 160px;
      height: 160px;
    }

    p {
      padding-top: 10px;
    }

    .name {
      font-size: 16px;
    }

    .desc {
      color: #999;
      height: 29px;
    }

    .price {
      color: $priceColor;
      font-size: 20px;
    }
  }
}

// 将分页容器样式移到这里，与 sub-container 平级
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  background-color: #fff;
  padding: 20px 0;
}

.filter-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;

  .el-form-item {
    margin-right: 20px;
  }
}
</style>
